import {useUserStore, useMainStore, useRequestStore} from '@/store'
import {menuRoutes, backstageRoutes, exceptionRoutes} from './modules'

export const createRouterGuards = router => {
  const userStore = useUserStore()
  const mainStore = useMainStore()
  const requestStore = useRequestStore()
  const whitePathList = ['/', '/login']
  const Loading = window['$loading'] || null
  router.beforeEach((to, from, next) => {
    Loading && Loading.start()
    requestStore.setHttpRequestList('all')
    if (to.path === '/') return next()
    const Xtoken = localStorage.getItem('X-token')
    const userInfo = userStore.getUserInfo()
    const token = Xtoken && userInfo?.time > Math.round(new Date().getTime() / 1000) || null
    if (token && to.path === '/login') return next({path: '/center', replace: true})
    if (!token && !whitePathList.includes(to.path)) {
      $message.error('您的登录已超时!')
      userStore.logout()
      whitePathList.includes(from.path) ? next(from.path) : next({path: '/login', replace: true})
      return
    }
    if (mainStore.isAddedRoute) return next()
    // 动态添加路由
    const routesArr = [...menuRoutes, ...backstageRoutes, ...exceptionRoutes]
    routesArr.forEach(item => router.addRoute(item))
    mainStore.setIsAddedRoute(true)
    next({...to, replace: true})
  })

  router.afterEach((to, from, failure) => {
    document.title = to?.meta?.title || document.title
    Loading && Loading.finish()
  })
}
